import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:joyagoo/pages/widget/JoyEmptyWidget.dart';
import '../config/app_colors.dart';
import '../model/productListModel.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/currency_manager.dart';
import 'joy_home_bloc.dart';
import 'widget/joy_product_card_widget.dart';
import 'package:easy_refresh/easy_refresh.dart';

import 'widget/search_result_widget.dart';
//JoySearchResultPage
class JoySearchResultPage extends StatefulWidget{

  final String searchword;
  final bool? isSearch;
  final int? seacrchImage;
  const JoySearchResultPage({Key? key, required this.searchword, this.isSearch = true,this.seacrchImage = 0}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return JoySearchResultPageState();
  }
  
}
class JoySearchResultPageState extends State<JoySearchResultPage>{

  late JoyHomeBloc mainHomeBloc;
  List searchProductList = [];
  late EasyRefreshController _refreshController;

  int pageSize = 20;
  int pageNo = 1;

  String error_aac = "";
  bool isNetError_aac = false;
  bool isShowButton = false;
  bool isLoading = false; // 新增加载状态

  String errorImage = "";

//createAt
// price
// sort
  String sortColumn = "createAt";

  ///0-正序
  /// 1-倒叙
  String orderBy = "0";



  // 货币变化监听器
  late CurrencyChangeListener _currencyChangeListener;

  String showTopTitle(){


    if(widget.seacrchImage == 1){
      return "search Image";
    }

    if(widget.isSearch == true){
      return "Search results for ${widget.searchword}";
    }
    return "Product list for ${widget.searchword}";
  }

  @override
  void initState() {
    super.initState();
    
    // 🔥 详细日志：页面初始化
    debugPrint("=== 搜索结果页面初始化 ===");
    debugPrint("搜索词: '${widget.searchword}'");
    debugPrint("搜索类型: ${widget.isSearch == true ? '文字搜索' : '分类搜索'}");
    debugPrint("图片搜索: ${widget.seacrchImage == 1 ? '是' : '否'}");
    debugPrint("页面参数: isSearch=${widget.isSearch}, seacrchImage=${widget.seacrchImage}");
    
    // // 🔥 设置状态栏颜色
    // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    //   statusBarColor: AppColors.backHomeYellowGround,
    //   statusBarIconBrightness: Brightness.dark, // 状态栏图标颜色（黑色）
    //   statusBarBrightness: Brightness.light, // iOS 状态栏文字颜色
    // ));
    
    _refreshController = EasyRefreshController(
        controlFinishRefresh: true, controlFinishLoad: true);
    
    // 初始化货币变化监听器
    _currencyChangeListener = (newCurrency, oldCurrency) {
      debugPrint('Search result page: Currency changed from ${oldCurrency.code} to ${newCurrency.code}');
      // 货币改变时刷新搜索结果页面数据
      _refreshSearchData();
    };
    
    // 添加货币变化监听器
    CurrencyManager.instance.addListener(_currencyChangeListener);
    
    debugPrint("=== 页面初始化完成，准备加载数据 ===");
  }

  // @override
  // void dispose() {
  //   // 移除货币变化监听器
  //   CurrencyManager.instance.removeListener(_currencyChangeListener);
  //   super.dispose();
  // }

  // 刷新搜索结果页面数据
  void _refreshSearchData() {
    if (mounted) {
      // 重置页码
      pageNo = 1;
      // 清空当前列表
      searchProductList.clear();
      // 设置加载状态
      isLoading = true;
      // 重新加载数据
      if (widget.isSearch == true) {
        mainHomeBloc.add(GetJOYSearchProductEvent(context, widget.searchword, pageNo, pageSize));
      } else {
        mainHomeBloc.add(GetJOYSearchCategoryProductEvent(context, widget.searchword, pageNo, pageSize,sortColumn: sortColumn,orderBy: orderBy));
      }
      
      // 不显示重复提示，只刷新数据
    }
  }

  @override
  void dispose() {
    // 🔥 恢复默认状态栏样式
    // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    //   statusBarColor: Colors.transparent,
    //   statusBarIconBrightness: Brightness.dark,
    //   statusBarBrightness: Brightness.light,
    // ));
    
    // 移除货币变化监听器
    CurrencyManager.instance.removeListener(_currencyChangeListener);
    _refreshController.dispose();
    super.dispose();
  }


  Widget kkbShowEmpty(){
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Column(
      children: [
        // Container(
        //   height: statusBarHeight,
        // ),
        Expanded(
          child:  JoyEmptyWidget(messageError: error_aac, isNetError: isNetError_aac, errorImagePath: "",isShowBtn: isShowButton, tapOnCallBack: (){
            // 点击重试时重新加载数据
            loadData();
          }),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.back();
        return false;
      },
      child: Scaffold(
        backgroundColor: Colors.red,
        // appBar: AppBar(
        //   backgroundColor: AppColors.backHomeYellowGround,
        //   title: _buildCustomAppBar(),
        // ),
        //   backgroundColor: AppColors.background,
        body: BlocMain()
      ),
    );
  }

  Widget BlocMain(){
    return  JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              AppColors.backHomeYellowGround,
              AppColors.background,
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildCustomAppBar(),

              Expanded(child: refrensh()),
            ],
          ),
        ),
      );
    }, create: (_) {
      mainHomeBloc = JoyHomeBloc();
      loadData();
      return mainHomeBloc;
    }, buildWhen: (previousState, state) {
      if(state is GetJOYSearchCategoryProductEventSuccess || state is GetJOYSearchProductEventSuccess){
        isLoading = false; // 结束加载
        isNetError_aac = false;
        isShowButton = true;
        
        // 🔥 详细日志：API成功响应
        debugPrint("=== API成功响应 ===");
        debugPrint("搜索词: '${widget.searchword}'");
        debugPrint("响应类型: ${state is GetJOYSearchCategoryProductEventSuccess ? '分类搜索成功' : '文字搜索成功'}");
        debugPrint("当前页码: $pageNo");
        
        dynamic stateData = (state is GetJOYSearchCategoryProductEventSuccess) 
            ? (state as GetJOYSearchCategoryProductEventSuccess).data 
            : (state as GetJOYSearchProductEventSuccess).data;
            
        debugPrint("原始响应数据: $stateData");
        
        if (stateData != null) {
          ProductListModel modellist = stateData as ProductListModel;
          
          // 🔥 详细日志：数据处理
          debugPrint("=== 数据处理 ===");
          debugPrint("返回商品数量: ${modellist.productModels.length}");
          debugPrint("每页期望数量: $pageSize");
          debugPrint("是否第一页: ${pageNo == 1}");
          debugPrint("处理前列表数量: ${searchProductList.length}");
          
          if(pageNo == 1){
            searchProductList.clear();
            debugPrint("清空列表，重新加载");
          }
          
          searchProductList.addAll(modellist.productModels);
          debugPrint("处理后列表数量: ${searchProductList.length}");
          
          // 🔥 详细日志：商品信息
          if(modellist.productModels.isNotEmpty) {
            debugPrint("=== 商品详情 ===");
            for(int i = 0; i < modellist.productModels.length && i < 3; i++) {
              var product = modellist.productModels[i];
              debugPrint("商品${i+1}: ${product.title} - ${product.price}");
            }
            if(modellist.productModels.length > 3) {
              debugPrint("... 还有${modellist.productModels.length - 3}个商品");
            }
          } else {
            debugPrint("⚠️ 警告：API返回的商品列表为空！");
          }
          
          _refreshController.resetHeader();
          _refreshController.finishLoad();
          _refreshController.finishRefresh();
          _refreshController.resetFooter();
          
          if(modellist.productModels.length < pageSize){
            debugPrint("数据不足一页，标记为无更多数据");
            _refreshController.finishLoad(IndicatorResult.noMore);
          }else{
            debugPrint("数据充足，可以继续加载");
            _refreshController.finishLoad();
          }

          if(searchProductList.isEmpty){
            error_aac = "No results found";
            debugPrint("❌ 最终结果：搜索无数据");
          } else {
            debugPrint("✅ 最终结果：搜索成功，共${searchProductList.length}个商品");
          }
        } else {
          debugPrint("❌ 错误：API返回数据为null");
        }

        return true;
      }

      if(state is GetJOYSearchCategoryProductEventFailure || state is GetJOYSearchProductEventFailure){
        isLoading = false; // 结束加载
        isNetError_aac = true;
        isShowButton = true;
        
        // 🔥 详细日志：API失败响应
        debugPrint("=== API失败响应 ===");
        debugPrint("搜索词: '${widget.searchword}'");
        debugPrint("失败类型: ${state is GetJOYSearchCategoryProductEventFailure ? '分类搜索失败' : '文字搜索失败'}");
        debugPrint("当前页码: $pageNo");
        
        dynamic errorMsg = (state is GetJOYSearchCategoryProductEventFailure) 
            ? (state as GetJOYSearchCategoryProductEventFailure).errMsg 
            : (state as GetJOYSearchProductEventFailure).errMsg;
            
        debugPrint("错误信息: $errorMsg");
        debugPrint("错误类型: ${errorMsg.runtimeType}");
        
        error_aac = (errorMsg as String?) ?? "Network error";
        debugPrint("设置错误显示: $error_aac");
        
        pageNo = pageNo - 1;
        if(pageNo <= 0){
          pageNo = 1;
        }
        debugPrint("页码回退到: $pageNo");
        
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();
        
        debugPrint("❌ 搜索失败，显示错误页面");
        return true;
      }
      if(state is GetSearchImageEventSuccess){
        isLoading = false; // 结束加载
        isNetError_aac = false;
        isShowButton = true;
        
        // 🔥 详细日志：图片搜索成功响应
        debugPrint("=== 图片搜索成功响应 ===");
        debugPrint("搜索词: '${widget.searchword}'");
        debugPrint("当前页码: $pageNo");
        
        dynamic imageData = (state as GetSearchImageEventSuccess).data;
        debugPrint("图片搜索原始数据: $imageData");
        
        if (imageData != null) {
          ProductListModel modellist = imageData as ProductListModel;
          
          debugPrint("=== 图片搜索结果处理 ===");
          debugPrint("返回商品数量: ${modellist.productModels.length}");
          debugPrint("每页期望数量: $pageSize");
          debugPrint("是否第一页: ${pageNo == 1}");
          debugPrint("处理前列表数量: ${searchProductList.length}");
          
          if(pageNo == 1){
            searchProductList.clear();
            debugPrint("清空列表，重新加载图片搜索结果");
          }
          
          searchProductList.addAll(modellist.productModels);
          debugPrint("处理后列表数量: ${searchProductList.length}");
          
          // 🔥 详细日志：图片搜索结果商品信息
          if(modellist.productModels.isNotEmpty) {
            debugPrint("=== 图片搜索结果商品详情 ===");
            for(int i = 0; i < modellist.productModels.length && i < 3; i++) {
              var product = modellist.productModels[i];
              debugPrint("商品${i+1}: ${product.title} - ${product.price}");
            }
            if(modellist.productModels.length > 3) {
              debugPrint("... 还有${modellist.productModels.length - 3}个商品");
            }
          } else {
            debugPrint("⚠️ 警告：图片搜索API返回的商品列表为空！");
          }
          
          _refreshController.resetHeader();
          _refreshController.finishLoad();
          _refreshController.finishRefresh();
          _refreshController.resetFooter();
          
          if(modellist.productModels.length < pageSize){
            debugPrint("图片搜索结果数据不足一页，标记为无更多数据");
            _refreshController.finishLoad(IndicatorResult.noMore);
          }else{
            debugPrint("图片搜索结果数据充足，可以继续加载");
            _refreshController.finishLoad();
          }

          if(searchProductList.isEmpty){
            error_aac = "No results found";
            debugPrint("❌ 最终结果：图片搜索无数据");
          } else {
            debugPrint("✅ 最终结果：图片搜索成功，共${searchProductList.length}个商品");
          }
        } else {
          debugPrint("❌ 错误：图片搜索API返回数据为null");
        }

        return true;
      }

      if(state is GetSearchImageEventFailure){
        isLoading = false; // 结束加载
        isNetError_aac = true;
        isShowButton = true;
        
        // 🔥 详细日志：图片搜索失败响应
        debugPrint("=== 图片搜索失败响应 ===");
        debugPrint("搜索词: '${widget.searchword}'");
        debugPrint("当前页码: $pageNo");
        
        dynamic imageErrorMsg = (state as GetSearchImageEventFailure).errMsg;
        debugPrint("图片搜索错误信息: $imageErrorMsg");
        debugPrint("错误类型: ${imageErrorMsg.runtimeType}");
        
        error_aac = (imageErrorMsg as String?) ?? "Network error";
        debugPrint("设置图片搜索错误显示: $error_aac");
        
        pageNo = pageNo - 1;
        if(pageNo <= 0){
          pageNo = 1;
        }
        debugPrint("页码回退到: $pageNo");
        
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();
        
        debugPrint("❌ 图片搜索失败，显示错误页面");
        return true;
      }


      return false;
    });
  }

  void loadData(){
    pageNo = 1;
    isLoading = true; // 开始加载
    
    // 🔥 详细日志：搜索参数
    debugPrint("=== 搜索开始 ===");
    debugPrint("搜索词: '${widget.searchword}'");
    debugPrint("搜索类型: ${widget.isSearch == true ? '文字搜索' : '分类搜索'}");
    debugPrint("图片搜索: ${widget.seacrchImage == 1 ? '是' : '否'}");
    debugPrint("页码: $pageNo, 每页数量: $pageSize");
    debugPrint("排序字段: $sortColumn, 排序方式: $orderBy");
    
    if(widget.seacrchImage == 1){
      debugPrint("执行图片搜索API: GetSearchNewImageEvent");
      mainHomeBloc.add(GetSearchNewImageEvent(context,widget.searchword));
    }else{
      if(widget.isSearch == true){
        debugPrint("执行文字搜索API: GetJOYSearchProductEvent");
        mainHomeBloc.add(GetJOYSearchProductEvent(context,widget.searchword,pageNo,pageSize));
      }else{
        debugPrint("执行分类搜索API: GetJOYSearchCategoryProductEvent");
        mainHomeBloc.add(GetJOYSearchCategoryProductEvent(context,widget.searchword,pageNo,pageSize,sortColumn: sortColumn,orderBy: orderBy));
      }
    }
  }

  void loadMoreData(){
    pageNo = pageNo + 1;
    
    // 🔥 详细日志：加载更多数据
    debugPrint("=== 加载更多数据 ===");
    debugPrint("搜索词: '${widget.searchword}'");
    debugPrint("页码: $pageNo, 每页数量: $pageSize");
    debugPrint("当前列表数量: ${searchProductList.length}");
    
    if(widget.isSearch == true){
      debugPrint("执行文字搜索API加载更多: GetJOYSearchProductEvent");
      mainHomeBloc.add(GetJOYSearchProductEvent(context,widget.searchword,pageNo,pageSize));
    }else{
      debugPrint("执行分类搜索API加载更多: GetJOYSearchCategoryProductEvent");
      mainHomeBloc.add(GetJOYSearchCategoryProductEvent(context,widget.searchword,pageNo,pageSize,sortColumn: sortColumn,orderBy: orderBy));
    }
  }


  // Widget kkbShowEmpty(){
  //   return KkbHomeEmptyWidget(messageError: error_kkb, isNetError: isNetError_kkb, errorImagePath: errorImage,isShowBtn: isShowButton, tapOnCallBack: (){
  //     loadData();
  //   });
  // }



  Widget refrensh() {
    return EasyRefresh(
        controller: _refreshController,
        // 🔥 设置下拉刷新样式 - 文字颜色为黑色
        header: const ClassicHeader(
          dragText: 'Pull to refresh',
          armedText: 'Release to refresh', 
          readyText: 'Refreshing...',
          processingText: 'Refreshing...',
          processedText: 'Refresh completed',
          noMoreText: 'No more data',
          failedText: 'Refresh failed',
          messageText: 'Last updated at %T',
          textStyle: TextStyle(color: Colors.black), // 🔥 设置文字颜色为黑色
          messageStyle: TextStyle(color: Colors.black54), // 🔥 设置消息文字颜色为黑色透明
        ),
        // 🔥 设置上拉加载样式 - 文字颜色为黑色  
        footer: const ClassicFooter(
          dragText: 'Pull to load',
          armedText: 'Release to load',
          readyText: 'Loading...',
          processingText: 'Loading...',
          processedText: 'Loading completed',
          noMoreText: 'No more data',
          failedText: 'Loading failed',
          messageText: 'Last updated at %T',
          textStyle: TextStyle(color: Colors.black), // 🔥 设置文字颜色为黑色
          messageStyle: TextStyle(color: Colors.black54), // 🔥 设置消息文字颜色为黑色透明
        ),
        onRefresh: () async {
          loadData ();
        },
        onLoad: (){
          loadMoreData();
        },
        child: _buildMain()
    );
  }

  // 自定义AppBar
  Widget _buildCustomAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12.r),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 8,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: AppColors.primaryVariant,
                size: 18.sp,
              ),
            ),
          ),
          SizedBox(width: 5,),
          Expanded(
            child: Center(
              child: (widget.seacrchImage == 1)?
              SearchResultWidget(
                content: widget.searchword,  // 或图片链接
                highlightColor: Colors.orange,  // 可选，默认黑色
                textStyle: TextStyle(fontSize: 16),  // 可选
              ):Text(
                showTopTitle(),
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: AppColors.textPrimary,
                ),
              ),
            ),
          ),
          SizedBox(width: 40.w), // 占位，保持标题居中
        ],
      ),
    );
  }

  Widget _buildMain(){
    // 正在加载中显示加载状态
    if(isLoading){
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF6B35)),
            ),
            SizedBox(height: 16.h),
            Text(
              'Searching...',
              style: TextStyle(
                fontSize: 16.sp,
                color: AppColors.textSecondary,
              ),
            ),
          ],
        ),
      );
    }
    
    // 加载完成后的状态判断
    if(searchProductList.isEmpty){
      return kkbShowEmpty();
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        padding: EdgeInsets.only(top: 12.h, bottom: 12.h),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.72,
          mainAxisSpacing: 12.h,
          crossAxisSpacing: 12.w,
        ),
        itemBuilder: (context, index) {
          ProductModel model = searchProductList[index];
          return Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.r),
              boxShadow: [
                BoxShadow(
                  color: AppColors.shadow.withOpacity(0.1),
                  blurRadius: 12,
                  offset: Offset(0, 4),
                ),
              ],
            ),
            child: JoyProductCardWidget(
              productModel: model,
              onTap: (){
                // 处理商品点击事件
              },
            ),
          );
        },
        itemCount: searchProductList.length,
      ),
    );
  }


}